<template>
  <d2-container>
    <template slot="header">
      <el-button size="small" type="primary" @click="showDialog(null)">新增文件</el-button>
    </template>
    <el-form :inline="true" :model="searchForm">
      <el-form-item label="文件类型" prop="contentType">
        <el-select clearable size="small" v-model="searchForm.contentType" placeholder="请选择">
          <el-option v-for="contentType in contentTypes" :key="contentType" :label="contentType" :value="contentType"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件来源" prop="fileFrom">
        <el-select clearable size="small" v-model="searchForm.fileFrom" placeholder="请选择">
          <el-option v-for="fileFrom in fileFroms" :key="fileFrom" :label="fileFrom" :value="fileFrom"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件名称">
        <el-input size="small" v-model="searchForm.oriName" placeholder="文件名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="plain" @click="currentPageInfo.current=1;fileList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="tableLoading" :data="files" style="width: 100%;" :stripe="true" :border="true">
      <el-table-column prop="id" label="文件ID" width="80"> </el-table-column>
      <el-table-column prop="oriName" label="文件名" width="180">
      </el-table-column>
      <el-table-column prop="contentType" label="文件类型" width="180">
      </el-table-column>
      <el-table-column prop="fileFrom" label="文件来源" width="180">
      </el-table-column>
      <el-table-column prop="url" label="url" width="180">
        <template slot-scope="scope">
          <a v-if="scope.row.contentType.indexOf('image')==-1" :href="scope.row.url">{{scope.row.url}}</a>
          <el-image v-if="scope.row.contentType.indexOf('image')>-1" :preview-src-list="[scope.row.url]" style="width: 100px; height: 100px" :src="scope.row.url" fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="action" label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="showDialog(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deletefile(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-loading="editLoading" :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form v-if="dialogVisible" :model="fileForm" :rules="rules" ref="editForm">
        <el-form-item label="文件名称" :label-width="formLabelWidth" prop="oriName">
          <el-row>
            <el-col :span="12">
              <el-input v-model="fileForm.oriName" autocomplete="off"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="文件上传" :label-width="formLabelWidth" prop="fileUuid">
          <el-input v-show="false" v-model="fileForm.fileUuid"></el-input>
          <el-upload class="upload-demo" :action="baseUrl + '/miniApp/upload'" :on-remove="handleRemove" :on-success="handleSuccess" :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed" :file-list="uploadFileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
    <template slot="footer">
      <p align="right">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPageInfo.current" :page-sizes="pageSizeOptions" :page-size="currentPageInfo.size" layout="total, sizes, prev, pager, next, jumper" :total="currentPageInfo.total">
        </el-pagination>
      </p>
    </template>
  </d2-container>
</template>

<script>
import api from "@/api";
export default {
  data () {
    return {
      baseUrl: process.env.VUE_APP_API,
      uploadFileList: [],
      searchForm: {},
      contentTypes: [],
      fileFroms: [],
      tableLoading: false,
      currentPageInfo: {
        current: 1,
        size: 10,
        total: 0
      },
      pageSizeOptions: [5, 10, 20, 40],
      editLoading: false,
      formLabelWidth: "120px",
      fileForm: {
        oriName: "",
        fileUuid: ""
      },
      files: [],
      currentfile: null,
      dialogVisible: false,
      rules: {
        oriName: [
          { required: true, message: "请输入文件名称", trigger: "blur" },
          { min: 0, max: 32, message: "长度在 0 到 32 个字符", trigger: "blur" }
        ],
        fileUuid: [{ required: true, message: "请上传文件", trigger: "blur" }]
      }
    };
  },
  computed: {
    dialogTitle () {
      return this.currentfile == null
        ? "新增文件"
        : "编辑文件 - " + this.currentfile.oriName;
    },
    isNew () {
      return this.currentfile == null;
    }
  },
  methods: {
    handleSuccess (response, file, fileList) {
      if (response.success) {
        this.fileForm.fileUuid = response.data;
        this.fileForm.oriName = file.name;
        this.fileForm.contentType = file.raw.type;
      } else {
        this.$nextTick(() => {
          this.uploadFileList = []
        })
        this.$message.error(
          response.msg
        );
      }
    },
    handleRemove (file, fileList) { },
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSizeChange (val) {
      this.currentPageInfo.size = val;
      this.currentPageInfo.current = 1;
      this.fileList();
    },
    handleCurrentChange (val) {
      this.currentPageInfo.current = val;
      this.fileList();
    },
    showDialog (currentfile) {
      this.currentfile = currentfile;
      var data = {
        fileUuid: "",
        oriName: "",
        contentType: ""
      }
      this.fileForm = currentfile ? { ...currentfile } : data
      this.dialogVisible = true;
    },
    deletefile (file) {
      this.$confirm('确定要删除"' + file.oriName + '"文件吗？', "删除文件", {
        type: "warning"
      }).then(async _ => {
        var res = await api.service
          .delete("/backManage/files", {
            params: {
              ids: file.id
            }
          })
          .catch(function(error) { });
        if (res) {
          this.$message({
            message: "删除成功！",
            type: "success"
          });
          this.fileList();
        }
      });
    },
    async listContentType () {
      var data = await api.service
        .get("/backManage/contentTypes", {})
        .catch(function(error) { });
      this.contentTypes = data;
    },
    async listFileFroms () {
      var data = await api.service
        .get("/backManage/fileFroms", {})
        .catch(function(error) { });
      this.fileFroms = data;
    },
    submit () {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.editLoading = true;
          var res = await api.service
            .post("/backManage/file", this.fileForm)
            .catch(function(error) { });
          if (res) {
            this.$message({
              message: this.isNew ? "新增成功！" : "修改成功！",
              type: "success"
            });
            this.dialogVisible = false;
            this.fileList();
            this.listContentType();
          }
          this.editLoading = false;
        }
      });
    },
    async fileList () {
      this.tableLoading = true;
      var data = await api.service
        .get("/backManage/files", {
          params: {
            oriName: this.searchForm.oriName,
            contentType: this.searchForm.contentType,
            fileFrom: this.searchForm.fileFrom,
            currentPage: this.currentPageInfo.current,
            pageSize: this.currentPageInfo.size
          }
        })
        .catch(function(error) { });
      this.currentPageInfo = data;
      this.files = data.records;
      this.tableLoading = false;
    }
  },
  created () {
    this.listContentType();
    this.fileList();
    this.listFileFroms();
  }
};
</script>
